<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

</head>

<body>
    <div id="app">
        <!-- 切换后保持原页面的数据 -->
        <button @click="msg='my-one'">组件一</button>
        <button @click="msg='my-two'">组件二</button>
        <!-- 所有被keep-alive包裹都有新的两个生命周期 -->
        <keep-alive>
            <component :is="msg"></component>
        </keep-alive>
    </div>

    <script>
        Vue.component("my-one", {
            created() {
                console.log("组件一创建了")
            },
            mounted() {
                console.log(123);
            },
            destroyed() {
                console.log("组件一销毁了")
            },
            activated() {
                console.log("activated生命周期被调用");
            },
            deactivated() {
                console.log("deactivated生命周期被调用");
            },
            template: `
            <div>
               <p>我是组件一</p>
               <input type='text'>
            </div>
            `,
        });
        Vue.component("my-two", {
            created() {
                console.log("组件二创建了");
                
            },
            destroyed() {
                console.log("组件二销毁了");
            },
            data(){
                return {
                    msg:'哈哈'
                }
            },
            template: `
            <div>
               <p>我是组件二</p>
               <p>{{msg}}</p>
               <button @click="msg='你好'">改变</button>
            </div>
            `,
        });

        var app = new Vue({
            el: "#app",
            data:{
                msg:"my-one"
            }
        });
    </script>
</body>

</html>